package org.song.model.threadlocal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author song
 * @date 2022/3/13 13:21
 * 自定义Web容器用来存储每次请求和响应的对象
 **/
public class WebContextUtil {

    // 使用ThreadLocal做线程隔离用来记录客户端每次请求线程的请求实例
    private static final ThreadLocal<HttpServletRequest> REQUEST_MAP = new ThreadLocal<>();

    // 使用ThreadLocal做线程隔离用来记录客户端每次请求线程的响应实例
    private static final ThreadLocal<HttpServletResponse> RESPONSE_MAP = new ThreadLocal<>();

    // ThreadLocal其实底层基于Map进行存储 做线程隔离 可以理解为 使用 Map<ThreadId , Object>

    /**
     * 设置本次线程的请求实例
     * @return
     */
    public static void setCurrentRequest( HttpServletRequest request ) {
        REQUEST_MAP.set( request );
    }

    /**
     * 设置本次线程的响应实例
     * @return
     */
    public static void setCurrentResponse( HttpServletResponse response ) {
        RESPONSE_MAP.set( response );
    }

    /**
     * 获取本次线程的请求实例
     * @return
     */
    public static HttpServletRequest getCurrentRequest() {
        return REQUEST_MAP.get();
    }

    /**
     * 获取本次线程的响应实例
     * @return
     */
    public static HttpServletResponse getCurrentResponse() {
        return RESPONSE_MAP.get();
    }

    /**
     * 移除本次线程的请求实例
     * @return
     */
    public static void removeCurrentRequest() {
        REQUEST_MAP.remove();
    }

    /**
     * 移除本次线程的响应实例
     * @return
     */
    public static void removeCurrentResponse() {
        RESPONSE_MAP.remove();
    }


}
